﻿
using Arction.Wpf.BindableCharting.SeriesPolar;
using Arction.Wpf.BindableCharting.Titles;
using Arction.Wpf.BindableCharting.Views.ViewPolar;
using DynamicData;
using Prism.Events;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using WPF_UI_Lightningchart.Events;

namespace WPF_UI_Lightningchart.ViewModels
{
    public class NyquistBindableControlViewModel : ReactiveObject
    {
        private readonly IEventAggregator _eventAggregator;
        public Dictionary<string, PointLineSeriesPolar> _pointLineSeriesPolar { get; private set; }
        public PointLineSeriesPolarCollection PointLineSeriesPolarCollection { get; private set; }

        public NyquistBindableControlViewModel(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
            _pointLineSeriesPolar = new Dictionary<string, PointLineSeriesPolar>();
            PointLineSeriesPolarCollection = new PointLineSeriesPolarCollection();
            _eventAggregator.GetEvent<SeriesAddedEvent>().Subscribe(OnOtherControlSeriesAdded);
        }

        public void AddSeriesToChart(string name, string type, PointLineSeriesPolar pointLineSeriesPolar)
        {
            
            if (type == "Nyquist")
            {
                _pointLineSeriesPolar[name] = pointLineSeriesPolar;
                var newPolarSeries = new PointLineSeriesPolar
                {
                    Points = _pointLineSeriesPolar[name].Points,
                    PointsVisible = _pointLineSeriesPolar[name].PointsVisible,
                    LineStyle = _pointLineSeriesPolar[name].LineStyle,
                    PointStyle = _pointLineSeriesPolar[name].PointStyle,
                    Title = _pointLineSeriesPolar[name].Title
                };
                // ps: 奈氏图好像不支持直接add数据源
                PointLineSeriesPolarCollection.Add(newPolarSeries);
            }
        }

        public void OnSeriesAdded(SensorViewModel sensorData)
        {
            if (!_pointLineSeriesPolar.ContainsKey(sensorData.SensorName))
            {
                _eventAggregator.GetEvent<SeriesAddedEvent>().Publish((sensorData.SensorName, "Nyquist"));

                AddSeriesToChart(sensorData.SensorName, "Nyquist", sensorData.AmpPhaProcessor.PolarSeries);
            }
        }

        private void OnOtherControlSeriesAdded((string sensorName, string type) type)
        {
            if (type.type == "Nyquist" && _pointLineSeriesPolar.ContainsKey(type.sensorName))
            {
                var phaseSeries = PointLineSeriesPolarCollection.FirstOrDefault(x => x.Title.Text == type.sensorName);
                PointLineSeriesPolarCollection.Remove(phaseSeries);
                _pointLineSeriesPolar.Remove(type.sensorName);
            }
        }
    }
}
